//
//  GPChatController.m
//  GuaPi
//
//  Created by 陈华 on 2017/6/19.
//  Copyright © 2017年 Joanlove. All rights reserved.
//

#import "GPChatController.h"

#import <IQKeyboardManager/IQKeyboardManager.h>
#import <MJRefresh/MJRefresh.h>
#import "KLPhotoBroswerController.h"
#import "PlayerManager.h"


#import "GPChatController+ChatToolView.h"           //聊天工具栏的分类
#import "GPChatController+Message.h"                //聊天消息的分类

#import "GPMessageCell.h"                           //消息的cell基类
#import "GPTextMessageCell.h"                       //文本消息的cell

#import "GPMessageItem.h"                           //消息模型
#import "GPChatViewModel.h"                         //聊天视图控制模型

#import "GPGoogleLocationController.h"

#import "GPUserProfileController.h"


@interface GPChatController () <GPMessageCellDelegate>

/**导航栏上的iconView*/
@property(nonatomic,weak) UIImageView *iconView;

@end

@implementation GPChatController

#pragma mark - 系统回调
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置UI
    [self setupUI];
   
    //记录属性
    self.isEmojiViewFirstLoading = YES;     //第一次加载表情键盘
    
    //监听
    //--监听键盘尺寸的变化通知
    [GPNoticationHelp addObserver:self selector:@selector(gp_keyboradWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [GPNoticationHelp addObserver:self selector:@selector(gp_videoVoiceCallEnd:) name:kVideoVoiceCallEndNotification object:nil];
    //--注册消息的回调
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
    //加载历史聊天记录
    [self loadHistoryData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    
    //关闭键盘
    [self.view endEditing:YES];
    [self emojiViewDisplay:NO animated:NO];
    [self photosViewDisplay:NO aimated:NO];
    [self voiceViewDisplay:NO aimated:NO];
}

- (void)dealloc
{
    //取消监听
    [GPNoticationHelp removeObserver:self];
    [[EMClient sharedClient].chatManager removeDelegate:self];
    
    if (self.voiceTimer) {
        [self.voiceTimer invalidate];
        self.voiceTimer = nil;
        self.voiceLength = 0;
    }
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    self.iconView.bounds = CGRectMake(0, 0, 30, 30);
    
}

#pragma mark - 设置UI
/**设置UI*/
- (void)setupUI
{
    //设置导航栏
    self.title = self.chatViewModel.toNickname;
    UIImageView *iconView = [[UIImageView alloc]init];
    iconView.frame = CGRectMake(0, 0, 30, 30);
    NSString *url = [KGetImageURL stringByAppendingPathComponent:self.chatViewModel.toAvatarURLPath];
    [iconView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"head_portrait_blue_small"]];
    if(SYSTEM_VERSION_GREATER_THAN(@"9.0")){
        //大于9.0的系统才有这个API，适配
        [iconView.widthAnchor constraintEqualToConstant:30].active = YES;
        [iconView.heightAnchor constraintEqualToConstant:30].active = YES;
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:iconView];
    iconView.userInteractionEnabled = YES;
    [iconView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(iconViewdidClicked)]];
    iconView.layer.cornerRadius = 15;
    iconView.layer.masksToBounds = YES;
    self.iconView = iconView;
    
    //设置tableView
    [self setupTableView];
    
    //设置toolView
    [self setupToolView];
    
    //设置约束
    [self setupConstraint];
}

/**设置TableView*/
- (void)setupTableView
{
    UITableView *tableView = [[UITableView alloc] init];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //其他属性
    self.tableView.estimatedRowHeight = 100.f;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = COLOR(241, 242, 246);
    
    //设置刷新控件
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    header.stateLabel.hidden = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    header.automaticallyChangeAlpha = YES;
    self.tableView.mj_header = header;
}

/**设置toolView*/
- (void)setupToolView
{
    GPChatToolView *toolView = [[GPChatToolView alloc] init];
    [self.view addSubview:toolView];
    self.toolView = toolView;
    
    //其他属性
    toolView.delegate = self;
}

/**设置约束*/
- (void)setupConstraint
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.toolView.mas_top);
    }];
    
    [self.toolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.height.mas_equalTo(100);
    }];
}

#pragma mark - 数据处理
/**加载历史数据*/
- (void)loadHistoryData
{
    [self.messages removeAllObjects];
    
    //根据conversationId获取会话,如果不存在则创建
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.chatViewModel.conversationId type:(EMConversationType)self.chatViewModel.chatType createIfNotExist:YES];
    
    //拉取当前会话的历史记录
    WEAKSELF
    [conversation loadMessagesStartFromId:nil count:20 searchDirection:EMMessageSearchDirectionUp completion:^(NSArray *aMessages, EMError *aError) {
        //判断错误
        if (aError) {
            
            return ;
        }
        
        //处理数据源
        for (EMMessage *message in aMessages) {
            
            //创建messageItem 并从本地加载昵称等用户信息
            GPMessageItem *messageItem = [self gp_setupMessageUserInfo:message];
            
            //添加消息
            [weakSelf messageArray:weakSelf.messages addMessage:messageItem];
        }
        
        //刷新表格并滚动
        [weakSelf.tableView reloadData];
        [weakSelf gp_scrollTableViewToBottom:NO];
        
    }];
}

/**加载更多数据*/
- (void)loadMoreData
{
    //根据conversationId获取会话,如果不存在则创建
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.chatViewModel.conversationId type:(EMConversationType)self.chatViewModel.chatType createIfNotExist:YES];
    
    //拉取历史记录
    WEAKSELF
    NSString *fromId = nil;
    if (self.messages.count) {
        GPMessageItem  *messageItem = self.messages.firstObject;
        fromId = messageItem.message.messageId;
    }
    [conversation loadMessagesStartFromId:fromId count:20 searchDirection:EMMessageSearchDirectionUp completion:^(NSArray *aMessages, EMError *aError) {
        
        //停止刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
        //判断错误
        if (aError) {
            
            return ;
        }
        
        //处理数据源
        NSMutableArray *arrayM = [NSMutableArray array];
        for (EMMessage *message in aMessages) {
            
            //创建messageItem 并从本地加载昵称等用户信息
            GPMessageItem *messageItem = [self gp_setupMessageUserInfo:message];
            
            //添加消息
            [weakSelf messageArray:arrayM addMessage:messageItem];
        }
        
        [arrayM addObjectsFromArray:weakSelf.messages];
        weakSelf.messages = [NSMutableArray arrayWithArray:arrayM];
        
        //刷新表格并滚动
        [weakSelf.tableView reloadData];
        if (aMessages.count) {
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:aMessages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
        
    }];
}


#pragma mark - UITableViewDelegate\UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取出模型
    GPMessageItem *message = self.messages[indexPath.row];
    
    //取出cell
    NSString * const ID = [GPMessageCell reuseIdWithMessage:message];
    Class cls = [GPMessageCell cellClassWithMessage:message];
    
    GPMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[cls alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
        cell.delegate = self;
    }
    
    
    //赋值
    cell.message = message;
    
    //返回
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取出模型
    GPMessageItem *messageItem = self.messages[indexPath.row];

    return messageItem.cellHeight;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //滚动后关闭键盘
    [self.view endEditing:YES];
    if (self.isEmojiViewShowing) {
        [self emojiViewDisplay:NO animated:YES];
    }
    if (self.isPhotosViewShowing) {
        [self photosViewDisplay:NO aimated:YES];
    }
    if (self.isVoiceViewShowing) {
        [self voiceViewDisplay:NO aimated:YES];
    }
}


#pragma mark - GPMessageCellDelegate
/**点击发送失败的icon*/
- (void)messageCell:(GPMessageCell *)cell didFailedIconClicked:(GPMessageItem *)messageItem
{
    //重新发送消息
    
    //更新消息的状态
    messageItem.message.status = EMMessageStatusDelivering;
    messageItem.message.localTime = [[NSDate new] timeIntervalSince1970] * 1000;
    
    //更新当前数据源
    [self.messages removeObject:messageItem];
    [self messageArray:self.messages addMessage:messageItem];
    [self.tableView reloadData];
    
    //将消息状态存储到数据库
    [[EMClient sharedClient].chatManager updateMessage:messageItem.message completion:nil];
    
    //重发消息
    WEAKSELF
    [[EMClient sharedClient].chatManager resendMessage:messageItem.message progress:^(int progress) {

    } completion:^(EMMessage *message, EMError *error) {
        [weakSelf.tableView reloadData];
    }];    
}
/**点击内容*/
- (void)messageCell:(GPMessageCell *)cell didContentClicked:(GPMessageItem *)message
{
    //判断
    switch (message.bodyType) {
        case EMMessageBodyTypeImage:
        {
            //获取数据源中的所有图片数组
            NSMutableArray *messageM = [NSMutableArray array];
            for (GPMessageItem *item in self.messages) {
                if (item.bodyType == EMMessageBodyTypeImage) {
                    [messageM addObject:item];
                }
            }
            
            //创建浏览器控制器
            KLPhotoBroswerController *vc = [[KLPhotoBroswerController alloc]init];
            vc.messages = messageM;
            vc.originMessages = self.messages;
            vc.selectedIndex = [messageM indexOfObject:message];
            
            //设置modal样式
            vc.modalPresentationStyle = UIModalPresentationCustom;
            
            //弹出控制器
            [self presentViewController:vc animated:YES completion:nil];
            
        }
            break;
            
        case EMMessageBodyTypeVoice:
        {
            //播放音频
            //刷新界面
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.messages indexOfObject:message] inSection:0];
            [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
            
            //更消息属性
             EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.chatViewModel.conversationId type:(EMConversationType)self.chatViewModel.chatType createIfNotExist:YES];
            EMError *error = nil;
            EMMessage *aMessage = message.message;
            NSDictionary *ext = @{@"isPlayed":@(YES)};
            aMessage.ext = ext;
            [conversation updateMessageChange:aMessage error:&error];
            
            // 如果本地的语音文件不存在，就要播放远程语音
            NSString *voicePath = message.fileLocalPath;
            if (![[NSFileManager defaultManager] fileExistsAtPath:voicePath]) {
                voicePath = message.fileURLPath;
            }
            
            if ([[PlayerManager sharedManager] playingFileName:voicePath]) { // 如果正在播放就停止播放
                [[PlayerManager sharedManager] stopPlaying];
            }
            else{
                //停止播放
                if ([[PlayerManager sharedManager] playing]) {
                    [[PlayerManager sharedManager] stopPlaying];
                }
                [[PlayerManager sharedManager] playAudioWithFileName:voicePath delegate:nil];
            }
        }
            break;
        
        case EMMessageBodyTypeLocation:
        {
            GPGoogleLocationController *vc = [[GPGoogleLocationController alloc] init];
            vc.latitude = message.latitude;
            vc.longitude = message.longitude;
            vc.address = message.address;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}


#pragma mark - 事件监听
/**视频音频通话结束*/
- (void)gp_videoVoiceCallEnd:(NSNotification *)notice
{
    //取出消息
    EMMessage *aMessage = notice.object;
    
    //调用环信的代理方法(使用方法违规)
    [self messagesDidReceive:@[aMessage]];
}

/**键盘尺寸变化通知*/
- (void)gp_keyboradWillChangeFrame:(NSNotification *)notice
{
    //取出键盘的相关信息
    NSDictionary *keyInfo = notice.userInfo;
    NSTimeInterval duration = [keyInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect beginRect = [keyInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endRect = [keyInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    BOOL display = beginRect.origin.y > endRect.origin.y;
    CGFloat heightM = endRect.size.height;//键盘的高度也会变化
//    CGFloat height = display?(beginRect.origin.y - endRect.origin.y):(endRect.origin.y - beginRect.origin.y);
    CGFloat height = display?heightM:-heightM;
    
    //其他键盘的改变
    if ((self.isEmojiViewShowing || self.isPhotosViewShowing || self.isVoiceViewShowing)&&display) {
        //关闭其他键盘--当前只有表情键盘需要关闭
        [self emojiViewDisplay:NO animated:NO];
        [self photosViewDisplay:NO aimated:NO];
        [self voiceViewDisplay:NO aimated:NO];
    }
    
    //系统键盘的改变
    [self systemKeyboardDisplay:display animated:YES keyboardHeight:height duration:duration];
}

/**导航栏右侧的头像按钮被点击*/
- (void)iconViewdidClicked
{
    GPUserProfileController *vc = [[GPUserProfileController alloc] init];
    vc.uid = self.chatViewModel.uid;
    vc.phone = self.chatViewModel.conversationId;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 工具方法
/**滚动tableView到底部*/
- (void)gp_scrollTableViewToBottom:(BOOL)animated
{
    if (self.tableView.contentSize.height > self.tableView.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
        [self.tableView setContentOffset:offset animated:animated];
    }
}

#pragma mark - 懒加载
- (GPEmojiKeyboard *)emojiView
{
    //记录
    self.isEmojiViewFirstLoading = _emojiView == nil;
    
    if (_emojiView == nil) {
        
        //创建emojieView
        GPEmojiKeyboard *emojiView = [[GPEmojiKeyboard alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, kEmojiViewHeight)];
        emojiView.delegate = self;
        emojiView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:emojiView];
        
        //添加约束
        [emojiView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(self.view.mas_bottom);
            make.height.mas_equalTo(kEmojiViewHeight);
        }];
        
        //赋值
        _emojiView = emojiView;
    }
    return _emojiView;
}

- (GPPhotosView *)photosView
{
    //记录
    self.isPhotosViewFirstLoading = _photosView == nil;
    if (_photosView == nil) {
        //创建photosView
        GPPhotosView *photosView = [[GPPhotosView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, kPhotosViewHeight)];
        photosView.delegate = self;
        [self.view addSubview:photosView];
        
        //添加约束
        [photosView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(self.view.mas_bottom);
            make.height.mas_equalTo(kPhotosViewHeight);
        }];
        
        //赋值
        _photosView = photosView;
    }
    return _photosView;
}

- (GPVoiceView *)voiceView
{
    //记录
    self.isVoiceViewFirstLoading = _voiceView == nil;
    if (_voiceView == nil) {
        //创建voiceView
        GPVoiceView *voiceView = [[GPVoiceView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, kVoiceViewHeight)];
        voiceView.delegate = self;
        [self.view addSubview:voiceView];
        
        //添加约束
        [voiceView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(self.view.mas_bottom);
            make.height.mas_equalTo(kPhotosViewHeight);
        }];
        
        //赋值
        _voiceView = voiceView;
    }
    return _voiceView;
}

- (NSMutableArray *)messages
{
    if (_messages == nil) {
        _messages = [NSMutableArray array];
    }
    return _messages;
}



@end
